package com.gxa.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 */
@Component
@Slf4j
public class JwtUtil {
    
    // JWT密钥
    private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    
    // Token过期时间（24小时）
    private static final long EXPIRATION_TIME = 24 * 60 * 60 * 1000;
    
    /**
     * 生成JWT Token
     * @param employeeId 员工ID
     * @param operatorLevel 操作员等级
     * @return JWT Token
     */
    public String generateToken(Integer employeeId, Integer operatorLevel) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("employeeId", employeeId);
        claims.put("operatorLevel", operatorLevel);
        
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SECRET_KEY)
                .compact();
    }
    
    /**
     * 从Token中获取员工ID
     * @param token JWT Token
     * @return 员工ID
     */
    public Integer getEmployeeIdFromToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            return claims.get("employeeId", Integer.class);
        } catch (Exception e) {
            log.error("从Token中获取员工ID失败", e);
            return null;
        }
    }
    
    /**
     * 从Token中获取操作员等级
     * @param token JWT Token
     * @return 操作员等级
     */
    public Integer getOperatorLevelFromToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            return claims.get("operatorLevel", Integer.class);
        } catch (Exception e) {
            log.error("从Token中获取操作员等级失败", e);
            return null;
        }
    }
    
    /**
     * 验证Token是否有效
     * @param token JWT Token
     * @return 是否有效
     */
    public boolean validateToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            return !claims.getExpiration().before(new Date());
        } catch (Exception e) {
            log.error("Token验证失败", e);
            return false;
        }
    }
    
    /**
     * 从Token中获取Claims
     * @param token JWT Token
     * @return Claims
     */
    private Claims getClaimsFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
} 